package com.mystore.author.security.manager;

import com.mystore.framework.pojo.LoginUser;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class SecurityDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> ConfigAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        System.err.println(authentication.getPrincipal());
        for (ConfigAttribute configAttribute : ConfigAttributes) {
            String needRole = configAttribute.getAttribute();
            System.err.println(needRole);
            if (needRole.equals("NOT_LOGIN")) {//如果角色列表返回的是NOT_LOGIN则表示未登录
                throw new AccessDeniedException("需要登陆！");
            }
            if(needRole.equals("NEED_LOGIN")){
                //匿名用户直接爬去登录
                if(authentication.getPrincipal()!=null&&authentication.getPrincipal().getClass().equals(LoginUser.class))
                    return;
                else
                    throw new AccessDeniedException("需要登陆！");
            }
            System.err.println("验证角色ing......");
            if(needRole.equals("NOT_NEED_ROLE"))//如果是NOT_NEED_ROLE则说明这个访问路径任何人都可以访问
                return;
//            获取登陆用户的角色 通过authentication.getAuthorities()获取
            System.out.println(authentication.getPrincipal());
            if(authentication.getPrincipal()==null||!authentication.getPrincipal().getClass().equals(LoginUser.class))
                throw new AccessDeniedException("权限不足，请联系管理员！");
            Collection<? extends GrantedAuthority> authorities = ((LoginUser)(authentication.getPrincipal())).getAuthorities();
            System.err.println(authorities.size());
            for (GrantedAuthority authority : authorities) {
                System.err.println(authority);
                if (authority.getAuthority().equals(needRole)) {//needRole 是通过数据库里面查找到访问该路径的角色（通过SecurityFilter类查询到的），这里与登陆用户所拥有的角色对比
                    return;//如果匹配上，即可访问该路径
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
